{% extends 'base.html' %}
{% load static %}

{% block title %}任务管理 - CFS Web System{% endblock %}

{% block extra_css %}
<style>
.task-card {
    border: 1px solid #dee2e6;
    border-radius: 8px;
    margin-bottom: 15px;
    transition: all 0.2s;
}

.task-card:hover {
    box-shadow: 0 2px 8px rgba(0,0,0,0.1);
}

.task-header {
    padding: 15px 20px;
    border-bottom: 1px solid #dee2e6;
    background: #f8f9fa;
    border-radius: 8px 8px 0 0;
}

.task-body {
    padding: 15px 20px;
}

.task-footer {
    padding: 10px 20px;
    border-top: 1px solid #dee2e6;
    background: #f8f9fa;
    border-radius: 0 0 8px 8px;
}

.task-status {
    font-size: 0.75rem;
    padding: 4px 8px;
    border-radius: 12px;
    font-weight: 500;
    text-transform: uppercase;
}

.task-status.pending {
    background: #fff3cd;
    color: #856404;
    border: 1px solid #ffeaa7;
}

.task-status.processing {
    background: #cce5ff;
    color: #004085;
    border: 1px solid #99d6ff;
}

.task-status.completed {
    background: #d4edda;
    color: #155724;
    border: 1px solid #c3e6cb;
}

.task-status.failed {
    background: #f8d7da;
    color: #721c24;
    border: 1px solid #f5c6cb;
}

.task-priority {
    font-size: 0.75rem;
    padding: 2px 6px;
    border-radius: 8px;
    font-weight: 500;
}

.task-priority.low {
    background: #e9ecef;
    color: #6c757d;
}

.task-priority.normal {
    background: #cce5ff;
    color: #004085;
}

.task-priority.high {
    background: #fff3cd;
    color: #856404;
}

.task-priority.urgent {
    background: #f8d7da;
    color: #721c24;
}

.progress-wrapper {
    position: relative;
    margin: 10px 0;
}

.progress {
    height: 6px;
    border-radius: 3px;
    overflow: hidden;
    background: #e9ecef;
}

.progress-bar {
    transition: width 0.3s ease;
}

.progress-text {
    position: absolute;
    right: 0;
    top: -20px;
    font-size: 0.75rem;
    color: #6c757d;
}

.file-list {
    max-height: 100px;
    overflow-y: auto;
}

.file-item {
    display: flex;
    align-items: center;
    padding: 4px 0;
    font-size: 0.875rem;
}

.file-icon {
    width: 16px;
    margin-right: 8px;
    flex-shrink: 0;
}

.stats-card {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    color: white;
    border-radius: 10px;
    padding: 20px;
    margin-bottom: 20px;
}

.stats-item {
    text-align: center;
}

.stats-number {
    font-size: 2rem;
    font-weight: bold;
    margin-bottom: 5px;
}

.stats-label {
    font-size: 0.875rem;
    opacity: 0.9;
}

.filter-section {
    background: #f8f9fa;
    border-radius: 8px;
    padding: 20px;
    margin-bottom: 20px;
}

.quick-actions {
    display: flex;
    gap: 10px;
    margin-bottom: 20px;
}

.action-btn {
    flex: 1;
    padding: 10px;
    border: 1px solid #dee2e6;
    border-radius: 6px;
    background: white;
    text-decoration: none;
    color: #495057;
    text-align: center;
    transition: all 0.2s;
}

.action-btn:hover {
    background: #e9ecef;
    color: #495057;
    text-decoration: none;
}

.empty-state {
    text-align: center;
    padding: 60px 20px;
    color: #6c757d;
}

.empty-state i {
    font-size: 4rem;
    margin-bottom: 20px;
    opacity: 0.5;
}

.task-actions {
    display: flex;
    gap: 5px;
}

.btn-sm {
    padding: 0.25rem 0.5rem;
    font-size: 0.75rem;
}

.task-meta {
    display: flex;
    gap: 15px;
    font-size: 0.875rem;
    color: #6c757d;
    margin-top: 10px;
}

.task-description {
    color: #495057;
    margin: 8px 0;
}

.pagination-wrapper {
    display: flex;
    justify-content: center;
    margin-top: 30px;
}

@media (max-width: 768px) {
    .task-meta {
        flex-direction: column;
        gap: 5px;
    }
    
    .quick-actions {
        flex-direction: column;
    }
    
    .task-actions {
        flex-wrap: wrap;
    }
}
</style>
{% endblock %}

{% block content %}
<div class="container-fluid">
    <!-- 统计卡片 -->
    <div class="stats-card">
        <div class="row">
            <div class="col-md-3 col-6">
                <div class="stats-item">
                    <div class="stats-number" id="totalTasks">0</div>
                    <div class="stats-label">总任务数</div>
                </div>
            </div>
            <div class="col-md-3 col-6">
                <div class="stats-item">
                    <div class="stats-number" id="processingTasks">0</div>
                    <div class="stats-label">处理中</div>
                </div>
            </div>
            <div class="col-md-3 col-6">
                <div class="stats-item">
                    <div class="stats-number" id="completedTasks">0</div>
                    <div class="stats-label">已完成</div>
                </div>
            </div>
            <div class="col-md-3 col-6">
                <div class="stats-item">
                    <div class="stats-number" id="failedTasks">0</div>
                    <div class="stats-label">失败</div>
                </div>
            </div>
        </div>
    </div>

    <!-- 快速操作 -->
    <div class="quick-actions">
        <a href="{% url 'data_processing:data_generation' %}" class="action-btn">
            <i class="fas fa-plus me-2"></i>新建任务
        </a>
        <button type="button" class="action-btn" id="refreshTasks">
            <i class="fas fa-sync-alt me-2"></i>刷新列表
        </button>
        <button type="button" class="action-btn" id="exportTasks">
            <i class="fas fa-download me-2"></i>导出任务
        </button>
        <button type="button" class="action-btn" id="clearCompleted">
            <i class="fas fa-trash me-2"></i>清理已完成
        </button>
    </div>

    <div class="row">
        <div class="col-lg-3">
            <!-- 过滤器 -->
            <div class="filter-section">
                <h6 class="mb-3">
                    <i class="fas fa-filter me-2"></i>筛选条件
                </h6>
                
                <div class="mb-3">
                    <label class="form-label">状态</label>
                    <select class="form-select form-select-sm" id="statusFilter">
                        <option value="">所有状态</option>
                        <option value="pending">等待中</option>
                        <option value="processing">处理中</option>
                        <option value="completed">已完成</option>
                        <option value="failed">失败</option>
                    </select>
                </div>
                
                <div class="mb-3">
                    <label class="form-label">优先级</label>
                    <select class="form-select form-select-sm" id="priorityFilter">
                        <option value="">所有优先级</option>
                        <option value="low">低</option>
                        <option value="normal">普通</option>
                        <option value="high">高</option>
                        <option value="urgent">紧急</option>
                    </select>
                </div>
                
                <div class="mb-3">
                    <label class="form-label">时间范围</label>
                    <select class="form-select form-select-sm" id="timeFilter">
                        <option value="">所有时间</option>
                        <option value="today">今天</option>
                        <option value="week">本周</option>
                        <option value="month">本月</option>
                    </select>
                </div>
                
                <div class="mb-3">
                    <label class="form-label">搜索</label>
                    <input type="text" class="form-control form-control-sm" id="searchInput" placeholder="搜索任务...">
                </div>
                
                <button type="button" class="btn btn-outline-secondary btn-sm w-100" id="clearFilters">
                    <i class="fas fa-times me-1"></i>清除筛选
                </button>
            </div>
        </div>
        
        <div class="col-lg-9">
            <!-- 排序和视图选项 -->
            <div class="d-flex justify-content-between align-items-center mb-3">
                <div class="d-flex align-items-center gap-3">
                    <span class="text-muted">排序:</span>
                    <select class="form-select form-select-sm" id="sortBy" style="width: auto;">
                        <option value="-created_at">创建时间(新到旧)</option>
                        <option value="created_at">创建时间(旧到新)</option>
                        <option value="-updated_at">更新时间(新到旧)</option>
                        <option value="priority">优先级</option>
                        <option value="status">状态</option>
                    </select>
                </div>
                
                <div class="d-flex align-items-center gap-2">
                    <span class="text-muted" id="taskCount">共 0 个任务</span>
                    <div class="btn-group" role="group">
                        <button type="button" class="btn btn-outline-secondary btn-sm active" id="cardView">
                            <i class="fas fa-th-large"></i>
                        </button>
                        <button type="button" class="btn btn-outline-secondary btn-sm" id="listView">
                            <i class="fas fa-list"></i>
                        </button>
                    </div>
                </div>
            </div>
            
            <!-- 任务列表 -->
            <div id="taskList">
                <!-- 任务将通过JavaScript动态加载 -->
            </div>
            
            <!-- 加载状态 -->
            <div class="text-center py-4" id="loadingState" style="display: none;">
                <div class="spinner-border" role="status">
                    <span class="visually-hidden">加载中...</span>
                </div>
                <div class="mt-2 text-muted">加载任务列表...</div>
            </div>
            
            <!-- 空状态 -->
            <div class="empty-state" id="emptyState" style="display: none;">
                <i class="fas fa-tasks"></i>
                <h5>暂无任务</h5>
                <p class="text-muted">还没有创建任何任务，点击上方"新建任务"开始吧！</p>
                <a href="{% url 'data_processing:data_generation' %}" class="btn btn-primary">
                    <i class="fas fa-plus me-2"></i>创建第一个任务
                </a>
            </div>
            
            <!-- 分页 -->
            <div class="pagination-wrapper" id="paginationWrapper" style="display: none;">
                <nav>
                    <ul class="pagination" id="pagination">
                        <!-- 分页将通过JavaScript动态生成 -->
                    </ul>
                </nav>
            </div>
        </div>
    </div>
</div>

<!-- 任务详情模态框 -->
<div class="modal fade" id="taskDetailModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">
                    <i class="fas fa-info-circle me-2"></i>任务详情
                </h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body" id="taskDetailContent">
                <!-- 详情内容将通过JavaScript动态加载 -->
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">关闭</button>
                <button type="button" class="btn btn-primary" id="downloadResult" style="display: none;">
                    <i class="fas fa-download me-1"></i>下载结果
                </button>
            </div>
        </div>
    </div>
</div>

<!-- 删除确认模态框 -->
<div class="modal fade" id="deleteModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">
                    <i class="fas fa-exclamation-triangle text-warning me-2"></i>确认删除
                </h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <p>确定要删除这个任务吗？此操作不可撤销。</p>
                <div class="alert alert-warning">
                    <i class="fas fa-info-circle me-2"></i>
                    <strong>注意：</strong>删除任务将同时删除相关的文件和结果。
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                <button type="button" class="btn btn-danger" id="confirmDelete">
                    <i class="fas fa-trash me-1"></i>确认删除
                </button>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block extra_js %}
<script>
$(document).ready(function() {
    // 全局变量
    let currentPage = 1;
    let currentView = 'card';
    let deleteTaskId = null;
    let autoRefreshInterval = null;
    
    // 初始化
    initializePage();
    
    function initializePage() {
        loadTaskStats();
        loadTasks();
        bindEvents();
        startAutoRefresh();
    }
    
    // 绑定事件
    function bindEvents() {
        // 筛选和搜索
        $('#statusFilter, #priorityFilter, #timeFilter, #sortBy').on('change', function() {
            currentPage = 1;
            loadTasks();
        });
        
        $('#searchInput').on('input', debounce(function() {
            currentPage = 1;
            loadTasks();
        }, 500));
        
        // 清除筛选
        $('#clearFilters').on('click', function() {
            $('#statusFilter, #priorityFilter, #timeFilter').val('');
            $('#searchInput').val('');
            currentPage = 1;
            loadTasks();
        });
        
        // 视图切换
        $('#cardView, #listView').on('click', function() {
            $('.btn-group .btn').removeClass('active');
            $(this).addClass('active');
            currentView = $(this).attr('id') === 'cardView' ? 'card' : 'list';
            loadTasks();
        });
        
        // 快速操作
        $('#refreshTasks').on('click', function() {
            loadTaskStats();
            loadTasks();
            showNotification('任务列表已刷新', 'success');
        });
        
        $('#exportTasks').on('click', exportTasks);
        $('#clearCompleted').on('click', clearCompletedTasks);
        
        // 任务操作
        $(document).on('click', '.view-task', viewTaskDetail);
        $(document).on('click', '.delete-task', function() {
            deleteTaskId = $(this).data('task-id');
            $('#deleteModal').modal('show');
        });
        
        $(document).on('click', '.download-result', downloadTaskResult);
        $(document).on('click', '.retry-task', retryTask);
        $(document).on('click', '.cancel-task', cancelTask);
        
        // 模态框操作
        $('#confirmDelete').on('click', deleteTask);
        $('#downloadResult').on('click', function() {
            const taskId = $(this).data('task-id');
            downloadTaskResult.call($(`[data-task-id="${taskId}"]`)[0]);
        });
    }
    
    // 加载任务统计
    function loadTaskStats() {
        $.ajax({
            url: '/api/tasks/stats/',
            method: 'GET',
            success: function(data) {
                $('#totalTasks').text(data.total || 0);
                $('#processingTasks').text(data.processing || 0);
                $('#completedTasks').text(data.completed || 0);
                $('#failedTasks').text(data.failed || 0);
            },
            error: function() {
                console.error('加载统计数据失败');
            }
        });
    }
    
    // 加载任务列表
    function loadTasks() {
        $('#loadingState').show();
        $('#taskList').empty();
        $('#emptyState').hide();
        
        const params = {
            page: currentPage,
            status: $('#statusFilter').val(),
            priority: $('#priorityFilter').val(),
            time_range: $('#timeFilter').val(),
            search: $('#searchInput').val(),
            ordering: $('#sortBy').val()
        };
        
        $.ajax({
            url: '/api/tasks/',
            method: 'GET',
            data: params,
            success: function(data) {
                const tasks = data.results || data;
                const total = data.count || tasks.length;
                
                $('#taskCount').text(`共 ${total} 个任务`);
                
                if (tasks.length === 0) {
                    $('#emptyState').show();
                    $('#paginationWrapper').hide();
                } else {
                    renderTasks(tasks);
                    if (data.count && data.count > 20) {
                        renderPagination(data);
                        $('#paginationWrapper').show();
                    } else {
                        $('#paginationWrapper').hide();
                    }
                }
            },
            error: function() {
                showNotification('加载任务列表失败', 'error');
                $('#emptyState').show();
            },
            complete: function() {
                $('#loadingState').hide();
            }
        });
    }
    
    // 渲染任务列表
    function renderTasks(tasks) {
        const taskList = $('#taskList');
        taskList.empty();
        
        tasks.forEach(task => {
            const taskElement = currentView === 'card' ? renderTaskCard(task) : renderTaskRow(task);
            taskList.append(taskElement);
        });
    }
    
    // 渲染任务卡片
    function renderTaskCard(task) {
        const statusText = getStatusText(task.status);
        const priorityText = getPriorityText(task.priority);
        const progress = task.progress || 0;
        
        return $(`
            <div class="task-card">
                <div class="task-header">
                    <div class="d-flex justify-content-between align-items-center">
                        <div class="d-flex align-items-center gap-2">
                            <h6 class="mb-0">${task.description || '数据处理任务'}</h6>
                            <span class="task-priority ${task.priority}">${priorityText}</span>
                        </div>
                        <span class="task-status ${task.status}">${statusText}</span>
                    </div>
                </div>
                
                <div class="task-body">
                    <div class="task-description">
                        ${task.template_name ? `模板: ${task.template_name}` : ''}
                    </div>
                    
                    ${task.status === 'processing' ? `
                        <div class="progress-wrapper">
                            <div class="progress-text">${progress}%</div>
                            <div class="progress">
                                <div class="progress-bar bg-primary" style="width: ${progress}%"></div>
                            </div>
                        </div>
                    ` : ''}
                    
                    <div class="file-list">
                        ${renderFileList(task.files)}
                    </div>
                    
                    <div class="task-meta">
                        <span><i class="fas fa-calendar me-1"></i>${formatDate(task.created_at)}</span>
                        <span><i class="fas fa-clock me-1"></i>${formatDate(task.updated_at)}</span>
                        ${task.result_file ? `<span><i class="fas fa-file me-1"></i>有结果文件</span>` : ''}
                    </div>
                </div>
                
                <div class="task-footer">
                    <div class="task-actions">
                        <button type="button" class="btn btn-outline-primary btn-sm view-task" data-task-id="${task.id}">
                            <i class="fas fa-eye"></i> 查看
                        </button>
                        ${task.status === 'completed' && task.result_file ? `
                            <button type="button" class="btn btn-outline-success btn-sm download-result" data-task-id="${task.id}">
                                <i class="fas fa-download"></i> 下载
                            </button>
                        ` : ''}
                        ${task.status === 'failed' ? `
                            <button type="button" class="btn btn-outline-warning btn-sm retry-task" data-task-id="${task.id}">
                                <i class="fas fa-redo"></i> 重试
                            </button>
                        ` : ''}
                        ${task.status === 'processing' ? `
                            <button type="button" class="btn btn-outline-danger btn-sm cancel-task" data-task-id="${task.id}">
                                <i class="fas fa-stop"></i> 取消
                            </button>
                        ` : ''}
                        <button type="button" class="btn btn-outline-danger btn-sm delete-task" data-task-id="${task.id}">
                            <i class="fas fa-trash"></i> 删除
                        </button>
                    </div>
                </div>
            </div>
        `);
    }
    
    // 渲染任务行（列表视图）
    function renderTaskRow(task) {
        const statusText = getStatusText(task.status);
        const priorityText = getPriorityText(task.priority);
        
        return $(`
            <div class="task-card">
                <div class="task-body">
                    <div class="row align-items-center">
                        <div class="col-md-4">
                            <div class="d-flex align-items-center gap-2">
                                <strong>${task.description || '数据处理任务'}</strong>
                                <span class="task-priority ${task.priority}">${priorityText}</span>
                            </div>
                            <div class="text-muted small">${task.template_name || '无模板'}</div>
                        </div>
                        <div class="col-md-2">
                            <span class="task-status ${task.status}">${statusText}</span>
                        </div>
                        <div class="col-md-3">
                            <div class="small text-muted">
                                <div>创建: ${formatDate(task.created_at)}</div>
                                <div>更新: ${formatDate(task.updated_at)}</div>
                            </div>
                        </div>
                        <div class="col-md-3">
                            <div class="task-actions">
                                <button type="button" class="btn btn-outline-primary btn-sm view-task" data-task-id="${task.id}">
                                    <i class="fas fa-eye"></i>
                                </button>
                                ${task.status === 'completed' && task.result_file ? `
                                    <button type="button" class="btn btn-outline-success btn-sm download-result" data-task-id="${task.id}">
                                        <i class="fas fa-download"></i>
                                    </button>
                                ` : ''}
                                <button type="button" class="btn btn-outline-danger btn-sm delete-task" data-task-id="${task.id}">
                                    <i class="fas fa-trash"></i>
                                </button>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        `);
    }
    
    // 渲染文件列表
    function renderFileList(files) {
        if (!files || files.length === 0) {
            return '<div class="text-muted small">无文件</div>';
        }
        
        return files.map(file => `
            <div class="file-item">
                <i class="fas ${getFileIcon(file.name)} file-icon"></i>
                <span class="text-truncate">${file.name}</span>
            </div>
        `).join('');
    }
    
    // 获取文件图标
    function getFileIcon(filename) {
        const ext = filename.split('.').pop().toLowerCase();
        switch (ext) {
            case 'xlsx':
            case 'xls':
                return 'fa-file-excel text-success';
            case 'csv':
                return 'fa-file-csv text-info';
            case 'txt':
                return 'fa-file-alt text-secondary';
            default:
                return 'fa-file text-muted';
        }
    }
    
    // 获取状态文本
    function getStatusText(status) {
        switch (status) {
            case 'pending': return '等待中';
            case 'processing': return '处理中';
            case 'completed': return '已完成';
            case 'failed': return '失败';
            default: return '未知';
        }
    }
    
    // 获取优先级文本
    function getPriorityText(priority) {
        switch (priority) {
            case 'low': return '低';
            case 'normal': return '普通';
            case 'high': return '高';
            case 'urgent': return '紧急';
            default: return '普通';
        }
    }
    
    // 查看任务详情
    function viewTaskDetail() {
        const taskId = $(this).data('task-id');
        
        $.ajax({
            url: `/api/tasks/${taskId}/`,
            method: 'GET',
            success: function(task) {
                renderTaskDetail(task);
                $('#taskDetailModal').modal('show');
            },
            error: function() {
                showNotification('加载任务详情失败', 'error');
            }
        });
    }
    
    // 渲染任务详情
    function renderTaskDetail(task) {
        const statusText = getStatusText(task.status);
        const priorityText = getPriorityText(task.priority);
        
        const detailHtml = `
            <div class="row">
                <div class="col-md-6">
                    <h6>基本信息</h6>
                    <table class="table table-sm">
                        <tr><td>任务ID:</td><td>${task.id}</td></tr>
                        <tr><td>描述:</td><td>${task.description || '无'}</td></tr>
                        <tr><td>状态:</td><td><span class="task-status ${task.status}">${statusText}</span></td></tr>
                        <tr><td>优先级:</td><td><span class="task-priority ${task.priority}">${priorityText}</span></td></tr>
                        <tr><td>模板:</td><td>${task.template_name || '无'}</td></tr>
                        <tr><td>输出格式:</td><td>${task.output_format || '无'}</td></tr>
                    </table>
                </div>
                <div class="col-md-6">
                    <h6>时间信息</h6>
                    <table class="table table-sm">
                        <tr><td>创建时间:</td><td>${formatDate(task.created_at)}</td></tr>
                        <tr><td>开始时间:</td><td>${task.started_at ? formatDate(task.started_at) : '未开始'}</td></tr>
                        <tr><td>完成时间:</td><td>${task.completed_at ? formatDate(task.completed_at) : '未完成'}</td></tr>
                        <tr><td>更新时间:</td><td>${formatDate(task.updated_at)}</td></tr>
                    </table>
                </div>
            </div>
            
            ${task.status === 'processing' && task.progress ? `
                <div class="mt-3">
                    <h6>处理进度</h6>
                    <div class="progress">
                        <div class="progress-bar" style="width: ${task.progress}%">${task.progress}%</div>
                    </div>
                </div>
            ` : ''}
            
            <div class="mt-3">
                <h6>上传文件</h6>
                <div class="file-list">
                    ${renderFileList(task.files)}
                </div>
            </div>
            
            ${task.result_file ? `
                <div class="mt-3">
                    <h6>结果文件</h6>
                    <div class="d-flex align-items-center">
                        <i class="fas fa-file-excel text-success me-2"></i>
                        <span>${task.result_file}</span>
                    </div>
                </div>
            ` : ''}
            
            ${task.error_message ? `
                <div class="mt-3">
                    <h6>错误信息</h6>
                    <div class="alert alert-danger">
                        <pre class="mb-0">${task.error_message}</pre>
                    </div>
                </div>
            ` : ''}
            
            ${task.log ? `
                <div class="mt-3">
                    <h6>处理日志</h6>
                    <div class="bg-light p-3 rounded" style="max-height: 200px; overflow-y: auto;">
                        <pre class="mb-0 small">${task.log}</pre>
                    </div>
                </div>
            ` : ''}
        `;
        
        $('#taskDetailContent').html(detailHtml);
        
        // 设置下载按钮
        if (task.status === 'completed' && task.result_file) {
            $('#downloadResult').show().data('task-id', task.id);
        } else {
            $('#downloadResult').hide();
        }
    }
    
    // 下载任务结果
    function downloadTaskResult() {
        const taskId = $(this).data('task-id');
        window.open(`/api/tasks/${taskId}/download/`, '_blank');
    }
    
    // 重试任务
    function retryTask() {
        const taskId = $(this).data('task-id');
        
        $.ajax({
            url: `/api/tasks/${taskId}/retry/`,
            method: 'POST',
            success: function() {
                showNotification('任务已重新提交', 'success');
                loadTasks();
                loadTaskStats();
            },
            error: function() {
                showNotification('重试任务失败', 'error');
            }
        });
    }
    
    // 取消任务
    function cancelTask() {
        const taskId = $(this).data('task-id');
        
        if (!confirm('确定要取消这个任务吗？')) {
            return;
        }
        
        $.ajax({
            url: `/api/tasks/${taskId}/cancel/`,
            method: 'POST',
            success: function() {
                showNotification('任务已取消', 'success');
                loadTasks();
                loadTaskStats();
            },
            error: function() {
                showNotification('取消任务失败', 'error');
            }
        });
    }
    
    // 删除任务
    function deleteTask() {
        if (!deleteTaskId) return;
        
        $.ajax({
            url: `/api/tasks/${deleteTaskId}/`,
            method: 'DELETE',
            success: function() {
                showNotification('任务已删除', 'success');
                $('#deleteModal').modal('hide');
                loadTasks();
                loadTaskStats();
                deleteTaskId = null;
            },
            error: function() {
                showNotification('删除任务失败', 'error');
            }
        });
    }
    
    // 导出任务
    function exportTasks() {
        const params = {
            status: $('#statusFilter').val(),
            priority: $('#priorityFilter').val(),
            time_range: $('#timeFilter').val(),
            search: $('#searchInput').val(),
            format: 'excel'
        };
        
        const queryString = $.param(params);
        window.open(`/api/tasks/export/?${queryString}`, '_blank');
    }
    
    // 清理已完成任务
    function clearCompletedTasks() {
        if (!confirm('确定要删除所有已完成的任务吗？此操作不可撤销。')) {
            return;
        }
        
        $.ajax({
            url: '/api/tasks/clear_completed/',
            method: 'POST',
            success: function(data) {
                showNotification(`已删除 ${data.deleted_count} 个已完成任务`, 'success');
                loadTasks();
                loadTaskStats();
            },
            error: function() {
                showNotification('清理任务失败', 'error');
            }
        });
    }
    
    // 渲染分页
    function renderPagination(data) {
        const pagination = $('#pagination');
        pagination.empty();
        
        const totalPages = Math.ceil(data.count / 20);
        
        // 上一页
        pagination.append(`
            <li class="page-item ${currentPage === 1 ? 'disabled' : ''}">
                <a class="page-link" href="#" data-page="${currentPage - 1}">上一页</a>
            </li>
        `);
        
        // 页码
        for (let i = Math.max(1, currentPage - 2); i <= Math.min(totalPages, currentPage + 2); i++) {
            pagination.append(`
                <li class="page-item ${i === currentPage ? 'active' : ''}">
                    <a class="page-link" href="#" data-page="${i}">${i}</a>
                </li>
            `);
        }
        
        // 下一页
        pagination.append(`
            <li class="page-item ${currentPage === totalPages ? 'disabled' : ''}">
                <a class="page-link" href="#" data-page="${currentPage + 1}">下一页</a>
            </li>
        `);
        
        // 绑定分页事件
        pagination.find('.page-link').on('click', function(e) {
            e.preventDefault();
            const page = parseInt($(this).data('page'));
            if (page && page !== currentPage && page >= 1 && page <= totalPages) {
                currentPage = page;
                loadTasks();
            }
        });
    }
    
    // 自动刷新
    function startAutoRefresh() {
        autoRefreshInterval = setInterval(function() {
            // 只有在有处理中的任务时才自动刷新
            if ($('#processingTasks').text() !== '0') {
                loadTaskStats();
                loadTasks();
            }
        }, 30000); // 30秒刷新一次
    }
    
    // 停止自动刷新
    function stopAutoRefresh() {
        if (autoRefreshInterval) {
            clearInterval(autoRefreshInterval);
            autoRefreshInterval = null;
        }
    }
    
    // 页面卸载时停止自动刷新
    $(window).on('beforeunload', stopAutoRefresh);
    
    // 工具函数
    function formatDate(dateString) {
        const date = new Date(dateString);
        return date.toLocaleDateString('zh-CN') + ' ' + date.toLocaleTimeString('zh-CN', {hour: '2-digit', minute: '2-digit'});
    }
    
    function debounce(func, wait) {
        let timeout;
        return function executedFunction(...args) {
            const later = () => {
                clearTimeout(timeout);
                func(...args);
            };
            clearTimeout(timeout);
            timeout = setTimeout(later, wait);
        };
    }
    
    function showNotification(message, type = 'info') {
        // 这里可以集成通知组件
        console.log(`${type}: ${message}`);
        // 临时使用alert，实际项目中应该使用更好的通知组件
        if (type === 'error') {
            showError('错误: ' + message);
        }
    }
});
</script>
{% endblock %}